package org.example.base.websocket;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.example.base.common.model.UserModel;
import org.example.base.common.service.UserService;
import org.example.base.websocket.dao.MessageDao;
import org.example.base.websocket.model.MessageChatModel;
import org.example.core.constanct.CommonUtils;
import org.example.core.enums.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.PongMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PostConstruct;
import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 * Date: 2024/1/18 21:11
 */
@Component
public class ChatWebSocketHandler extends TextWebSocketHandler {

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    private Map<String, WebSocketSession> webSocketSessionMap = new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String path = session.getUri().getRawPath();
        String userId = path.substring(path.lastIndexOf("/") + 1);
        webSocketSessionMap.put(userId, session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //处理请求消息
        String content = message.getPayload();
        String kind = JSONUtil.parseObj(content).getStr("kind");
        if (StringUtils.hasText(kind) && "0".equals(kind)){
            JSONObject kindJsonObject = new JSONObject();
            kindJsonObject.put("kind", "1");
            session.sendMessage(new TextMessage(kindJsonObject.toString()));
            return;
        }
        MessageChatModel messageChatModel = JSONObject.parseObject(content, MessageChatModel.class);
        if (ObjectUtils.isEmpty(messageChatModel)) {
            session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.failure("参数不能为空"))));
            return;
        }
        String toContactId = messageChatModel.getToContactId();
        if (ObjectUtils.isEmpty(toContactId)) {
            session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.failure("联系人信息不能为空"))));
            return;
        }
        JSONObject fromUserJsonObject = JSONObject.parseObject(String.valueOf(messageChatModel.getFromUser()));
        String id = fromUserJsonObject.getString("id");//当前用户id
        if (ObjectUtils.isEmpty(id)) {
            session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.failure("当前用户id不能为空"))));
            return;
        }
        try {
            messageChatModel.setId(CommonUtils.getUUID().replaceAll("-", ""));
            messageChatModel.setStatus("success");
            //插入新的聊天数据
            int add = messageDao.insert(messageChatModel);
            if (add == 1) {
                //发送消息通知给指定的人
                WebSocketSession toContactSession = webSocketSessionMap.get(toContactId);
                if (!ObjectUtils.isEmpty(toContactSession) && toContactSession.isOpen()) {
                    //将发送人和接受人的id进行调换
                    messageChatModel.setToContactId(id);
                    JSONObject fromUser = JSONObject.parseObject(String.valueOf(messageChatModel.getFromUser()));
//                    fromUser.put("id", messageChatModel);
                    messageChatModel.setFromUser(fromUser);
                    toContactSession.sendMessage(new TextMessage(JSON.toJSONString(messageChatModel)));
                    //发送消息给当前用户通知操作已完成
                }
                //发送消息通知给发送人
                if (session.isOpen()){
                    session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.success())));
                }
                return;
            }
            session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.failure("新增失败"))));
        } catch (Exception e) {
            e.printStackTrace();
            session.sendMessage(new TextMessage(JSON.toJSONString(ApiResult.failure("操作失败"))));
        }
    }

    @PostConstruct
    public void initAllUserMsg() {
        userService.searchAll().stream().map(UserModel::getId).forEach(userId -> {
            webSocketSessionMap.put(userId, null);
        });
    }
}
